package com.innovation.ic.im.end.base.thread.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.innovation.ic.im.end.base.model.im_erp9.Account;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.RabbitMqConstants;
import com.innovation.ic.im.end.base.service.im_erp9.AccountRelationService;
import com.innovation.ic.im.end.base.service.im_erp9.AccountService;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @desc   监听erp删除供应商协同账号队列
 * @author linuo
 * @time   2023年4月20日09:21:07
 */
public class ListenErpScAccountDeleteQueueThread extends AbstractThread implements Runnable{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /** erp交换机 */
    private String exchange;

    public ListenErpScAccountDeleteQueueThread(Channel channel, String exchange, AccountService accountService, AccountRelationService accountRelationService) {
        this.channel = channel;
        this.exchange = exchange;
        this.accountService = accountService;
        this.accountRelationService = accountRelationService;
    }

    @SneakyThrows
    @Override
    public void run() {
        String routingKey = RabbitMqConstants.ERP_SC_ACCOUNT_DELETE_QUEUE;
        String queue = routingKey;
        channel.queueBind(queue, exchange, routingKey);
        channel.queueDeclare(queue, true, false, false, null);
        channel.exchangeDeclare(exchange, RabbitMqConstants.DIRECT_TYPE, true);
        Consumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String bodyString = new String(body);
                logger.info("接收到的队列:[{}]的消息为:[{}]", queue, bodyString);
                try {
                    JSONObject jsonObject = JSON.parseObject(bodyString);
                    if(jsonObject != null && !jsonObject.isEmpty()){
                        // 获取消息名称
                        String msgName = jsonObject.getString(RabbitMqConstants.MESSAGE_NAME_FIELD);
                        if(!msgName.equals(RabbitMqConstants.ERP_SC_ACCOUNT_DELETE_QUEUE)){
                            logger.info("mq消息中的方法为:[{}],与当前监听方法:[{}]不一致,不进行后续处理", msgName, RabbitMqConstants.ERP_GROUP_DELETE_QUEUE);
                            return;
                        }

                        // 获取消息体
                        JSONObject json = (JSONObject) jsonObject.get(RabbitMqConstants.MESSAGE_BODY_FIELD);
                        if(json != null && !json.isEmpty()){
                            String id = json.getString(RabbitMqConstants.ID);
                            if(!Strings.isNullOrEmpty(id)){
                                ServiceResult<Account> accountResult = accountService.findById(id);
                                Account account = accountResult.getResult();
                                if(account != null){
                                    // 删除历史供应商协同账号的聊天对数据
                                    chatPairService.deleteScChatPairData(account.getUsername());
                                }

                                // 根据ScAccountId删除账号关系表数据
                                ServiceResult<Integer> serviceResult = accountRelationService.deleteByScAccountId(id);
                                Integer result = serviceResult.getResult();
                                if(result != null && result > 0){
                                    logger.info("根据供应商协同账号id:[{}]删除账号关系表数据成功", id);
                                }

                                // 根据id删除账号表数据
                                ServiceResult<Integer> serviceResult1 = accountService.deleteById(id);
                                Integer result1 = serviceResult1.getResult();
                                if(result1 != null && result1 > 0){
                                    logger.info("根据id:[{}]删除账号表数据成功", id);
                                }
                            }else{
                                logger.info("消息体中id字段为空,无法进行后续处理");
                            }
                        }
                    }
                    logger.info("erp删除供应商协同账号队列消息处理结束");
                } catch (Exception e) {
                    logger.error("监听队列:[{}]时出现问题,原因:", queue, e);
                }
            }
        };
        channel.basicConsume(queue, true, callback);
    }
}